#!/usr/bin/env python
# -*- coding: utf-8 -*-

import hashlib
import os
from appJar import gui 
from PIL import Image, ImageTk
import app.face.face8pic as face8pic
import dataset
db = dataset.connect('sqlite:///resources//mydatabase.db') 
emotions = db['emotions'] # 数据库：表情包
pics = db['pics'] # 表：图片
lines = db['lines'] # 表：话语

def pic_md5(path):
    with open(path, 'rb') as f:  # 图片信息是二进制形式
        return hashlib.md5(f.read()).hexdigest()

def press(btn): #选定：
    md5 = app.getSpinBox("md5")
    em1 = app.getSpinBox("em1")
    em2 = app.getSpinBox("em2")
    print(btn,md5,em1,em2)
    pics.upsert(dict(em1=em1,em2=em2,md5=md5), ['md5'])
    print(pics.find_one(md5=md5))

def em1Change(btn):
    # print(btn,app.getSpinBox("em1"))
    app.changeSpinBox("em2",[em2["em2"] for em2 in emotions.find(em1=app.getSpinBox("em1").strip())])
    em2Change("em2")
    
def em2Change(btn):
    print(btn,app.getSpinBox("em1"),app.getSpinBox("em2"))
    ls = list(lines.find(used=0,em1=app.getSpinBox("em1").strip(),em2=app.getSpinBox("em2").replace("_","").strip()))
    print(ls)
    if ls:
        app.changeSpinBox("line",[line['line'] for line in ls])

def md5Change(btn):
    print(btn,app.getSpinBox("md5"))
    md5 = app.getSpinBox("md5").strip()
    photo = ImageTk.PhotoImage(Image.open(f"{os.getcwd()}\\tmp\\yige\\{md5}.{fileext}").resize((240,240)))
    app.setImageData("pic", photo, fmt="PhotoImage")

    md52s = [f.split('.')[0] for f in os.listdir(f"{os.getcwd()}\\tmp\\face")]
    
    if md5 in md52s:
        md52png = [f for f in os.listdir(f"{os.getcwd()}\\tmp\\face") if f.startswith(md5)][0]
        photo2 = ImageTk.PhotoImage(Image.open(f"{os.getcwd()}\\tmp\\face\\{md52png}").resize((240,240)))
    else:
        photo2 = ImageTk.PhotoImage(Image.open(f"{os.getcwd()}\\tmp\\yige\\{md5}.{fileext}").resize((240,240)))
    app.setImageData("photo2", photo2, fmt="PhotoImage")
    
    pic = pics.find_one(md5=md5)
    print(pic)
    if pic:
        app.setSpinBox("em1",pic.get("em1") if pic.get("em1") else "中性", callFunction=True)
        app.changeSpinBox("em2",[em2["em2"] for em2 in emotions.find(em1=app.getSpinBox("em1").strip())])
        app.setSpinBox("em2",pic.get("em2"), callFunction=True)
    em2Change("em2")      

def gen(btn):
    print(btn)
    md5 = app.getSpinBox("md5")
    line = app.getSpinBox("line")
    if line.strip() == "":
        line = app.getEntry("word")
    face8pic.convert(f"{os.getcwd()}\\tmp\\yige\\{md5}.{fileext}",line)
    photo2 = ImageTk.PhotoImage(Image.open(f"{os.getcwd()}\\tmp\\face\\{md5}.{line}.png").resize((240,240)))
    app.setImageData("photo2", photo2, fmt="PhotoImage")
    db['lines'].upsert({'used':1,'line':line},keys=['line'])

if __name__ == "__main__":
    fileext = "png"
    md5s = [f.replace(f".{fileext}",'') for f in os.listdir(f"{os.getcwd()}\\tmp\\yige")]
    md52s = [f.split('.')[0] for f in os.listdir(f"{os.getcwd()}\\tmp\\face")]
    md5s = [  md5 for md5 in md5s if md5 not in md52s]
    
    app = gui()
    md5 = md5s[0]
    photo = ImageTk.PhotoImage(Image.open(f"{os.getcwd()}\\tmp\\yige\\{md5}.{fileext}").resize((240,240)))
    app.addImageData("pic", photo, fmt="PhotoImage")
    app.addLabelSpinBox("md5", md5s)

    app.addLabelSpinBox("em1", ["中性","正向","负向"])
    app.addLabelSpinBox("em2", ['普通'])
    app.addLabelSpinBox("line", [line['line'] for line in lines.find(em1="中性",em2="普通")])
    app.addLabelEntry("word")

    app.setSpinBoxChangeFunction("md5",md5Change)
    app.setSpinBoxChangeFunction("em1",em1Change)
    app.setSpinBoxChangeFunction("em2",em2Change)
    
    app.setSpinBox("md5",md5, callFunction=False)
    app.setSpinBox("em1","中性", callFunction=False)
    app.setSpinBox("em2",'普通', callFunction=False)
        
    app.addButton("选定",  press)
    app.addButton("生成",  gen)
    
    
    if md5 in md52s:
        md52png = [f for f in os.listdir("face") if f.startswith(md5)][0]
        print(md5,md52png)
        photo2 = ImageTk.PhotoImage(Image.open(f"{os.getcwd()}\\tmp\\face\\{md52png}").resize((240,240)))
        app.addImageData("photo2", photo2, fmt="PhotoImage")
    else:
        photo2 = ImageTk.PhotoImage(Image.open(f"{os.getcwd()}\\tmp\\yige\\{md5}.{fileext}").resize((240,240)))
        app.addImageData("photo2", photo2, fmt="PhotoImage")
    
    app.setSpinBox("md5",md5, callFunction=True)
    app.go()
    
